'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class LoginController extends Controller {
  async login() {
    const { ctx } = this;

    // 获取前端传来的参数
    const { username, password } = ctx.request.body;

    // 在数据库中查找 登录的用户和登录的密码是否存在于数据库
    const data = await this.app.mysql.get('userlist', { username, password });

    if (data) {
      ctx.body = {
        code: 1,
        msg: '登录成功',
        token: jwt.sign(data.id, '1908A'),
      };
    } else {
      ctx.status = 401;

      ctx.body = {
        code: 0,
        msg: '用户名或者密码错误 请重试',
      };
    }
  }

  // 注册
  async sign() {
    const { ctx, app } = this;

    const { username, password } = ctx.request.body;

    const data = await app.mysql.get('userlist', { username });

    if (data) {

      ctx.status = 403;

      ctx.body = {
        code: 0,
        msg: '用户已注册',
      };
    } else {
      await app.mysql.insert('userlist', { username, password });

      ctx.body = {
        code: 1,
        msg: '注册成功',
      };
    }

  }

  // 获取用户信息
  async getUserInfo() {
    const { ctx, app } = this;

    const { authorization } = ctx.request.headers;

    try {
      // 解密token
      const id = jwt.verify(authorization, '1908A');

      const data = await app.mysql.get('userlist', { id });

      ctx.body = {
        code: 1,
        data,
      };

    } catch (error) {
      ctx.status = 401;
      ctx.body = {
        code: 0,
        msg: '登录已过期请重新登录',
      };
    }

  }

  async giteeLogin() {
    const { ctx, app } = this;

    const { code } = ctx.request.body;

    // 获取用户在码云中的token
    const res = await ctx.curl('https://gitee.com/oauth/token', {
      method: 'post',
      data: {
        grant_type: 'authorization_code',
        code,
        client_id: 'd38d8fd6243ccb93f0076f02c57336de802491411f650b2b18af8c2a59d98719',
        redirect_uri: 'http://10.1.33.16:8080/login',
        client_secret: '2a33ca464171ac3a5e3756691962b87697f5f3b957551b9c744724a358485cd0',
      },
      dataType: 'json',
    });

    const token = res.data.access_token;

    // 通过tokne换取用户详细信息
    const data = await ctx.curl(`https://gitee.com/api/v5/user?access_token=${token}`, { dataType: 'json' });

    console.log(data, '---');

    // 判断第第三方用户是否存在我的数据库中
    const user = await app.mysql.get('userlist', { id: data.data.id });

    if (!user) {
      // 如果第三方用户不存在与我的数据库中 就将用户添加到我的数据库
      await app.mysql.insert('userlist', {
        username: data.data.login,
        password: '123',
        name: data.data.name,
        id: data.data.id,
        img: data.data.avatar_url,
      });
    }

    ctx.body = {
      code: 1,
      token: jwt.sign(data.data.id, '1908A'),
    };
  }
}

module.exports = LoginController;
